/*
 * Mode Selector Panel Handler
 * 
 * Version: 1.0: This class is responsible for generating the Mode Selector Panel which lets user select the experiment
 * type to be set up as in Tempo, wherever applicable
 * 
 * Date: 12/05/2010
 * 
 * Licensed under Eclipse open source license
 */

package slhs.tempo.scriptGenerator;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.mlc.swing.layout.LayoutConstraintsManager;

import slhs.tempo.TableAnalyzer.TablePanelHandler;
import slhs.tempo.dataImporterUtilities.IOFileHandler;
import slhs.tempo.dataImporterUtilities.OutFileFields;

public class ModeSelectorScreenHandler extends JPanel implements PanelHandler {

    private static final ModeSelectorScreenHandler modeSelectorScreenHandler = new ModeSelectorScreenHandler();

    private static final String MODE_SELECTOR_PANEL_LAYOUT_XML_FILE = "MODE_SELECTOR_PANEL_LAYOUT.XML";
    private static final String EXPERIMENT_SETUP = "Experiment Setup - ";
    private static final String CONFIGURATION_SCREEN_CARD = "Startup Screen";
    private static final String PARSER_SCREEN_CARD = "Parser Screen";
    private static final String TABLE_SCREEN_CARD = "Table Screen";
    private static final String TEMPLATE_EDITOR = "----------Template Editor Utility----------";
    private static final String DATA_ANALYZER = "----------Data Import-Analyzer Utility----------";

    private Object[] tableColoumns = { "Subject", "Status", "Wave File", "Probe", "Probe Delay", "Reaction Time",
	    "Response", "Correct Response", "VRDelay", "Blink", "Prac/Fill/Exp", "Type", "Ctl/Rel", "Item Number",
	    "Stimulus Number", "Probe Point", "Script" };

    private static final int xPosition = 250;
    private static final int yPosition = 150;
    private static final int width = 860;
    private static final int height = 620;
    private int numberOfFiles = 0;
    private OutFileFields[] outFileFieldsArray;

    private final String[] functions = { DATA_ANALYZER, TEMPLATE_EDITOR };

    private static JFrame startupFrame;

    private JPanel modeSelectorBasePanel;
    private static JPanel screensHolderPanel;

    private JButton startButton;
    private JButton cancelButton;

    private JComboBox utilitySelector;
    private static JComboBox modeSelector;

    private ModeSelectorScreenHandler() {

	LookAndFeelManager lookAndFeelManager = new LookAndFeelManager();
	// lookAndFeelManager.setTheme("Nimbus");
	// lookAndFeelManager.initLookAndFeel();
	modeSelectorBasePanel = new JPanel();
	// modeSelectorBasePanel.setBackground(Color.WHITE);
	GroupLayout modeSelectorPanelLayout = new GroupLayout(modeSelectorBasePanel);
	modeSelectorBasePanel.setLayout(modeSelectorPanelLayout);

	initComponents();

	addComponents(modeSelectorPanelLayout);

    }

    public static ModeSelectorScreenHandler getInstance(JPanel basePanel, JFrame frame) {
	screensHolderPanel = basePanel;
	startupFrame = frame;
	return modeSelectorScreenHandler;

    }

    private void initComponents() {

	this.utilitySelector = new JComboBox(functions);
	utilitySelector.addActionListener(this);

	this.modeSelector = new JComboBox(UtilityConstants.EXPERIMENT_MODES);
	modeSelector.setEnabled(false);
	modeSelector.setForeground(Color.GRAY);
	modeSelector.addActionListener(this);

	this.startButton = new JButton("Start");
	startButton.addActionListener(this);

	this.cancelButton = new JButton("Cancel");
	cancelButton.addActionListener(this);
    }

    private void addComponents(GroupLayout probeTimingFormatPanelLayout) {
	LayoutConstraintsManager layoutConstraintsManager = LayoutConstraintsManager.getLayoutConstraintsManager(this
		.getClass().getResourceAsStream(MODE_SELECTOR_PANEL_LAYOUT_XML_FILE));
	LayoutManager panelLayout = layoutConstraintsManager.createLayout("panel", this);
	modeSelectorBasePanel.setLayout(panelLayout);

	modeSelectorBasePanel.add(utilitySelector, "utilitySelector");
	modeSelectorBasePanel.add(modeSelector, "modeSelector");
	modeSelectorBasePanel.add(cancelButton, "cancelButton");
	modeSelectorBasePanel.add(startButton, "startButton");
    }

    @Override
    public JPanel getPanel() {
	return modeSelectorBasePanel;
    }

    protected boolean draw(int x, int y, int width, int height) {
	startupFrame.setBounds(x, y, width, height);
	startupFrame.setResizable(false);
	return true;
    }

    private void setupConfigurationScreen() {
	JPanel startupBasePanel = (new StartupBasePanelHandler(screensHolderPanel, startupFrame)).getPanel();
	screensHolderPanel.add(startupBasePanel, CONFIGURATION_SCREEN_CARD);
	CardLayout basePanelLayout = (CardLayout) (screensHolderPanel.getLayout());
	basePanelLayout.show(screensHolderPanel, CONFIGURATION_SCREEN_CARD);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
	Object source = event.getSource();

	if (source.equals(cancelButton)) {
	    System.exit(0);
	}

	else if (source.equals(startButton) && modeSelector.isEnabled()) {
	    UtilityConstants.EXPERIMENT_TYPE = modeSelector.getSelectedItem().toString();
	    drawStartupFrame();

	} else if (source.equals(startButton) && !modeSelector.isEnabled()) {
	    /* This is what happens when Import-Analyze utility is used */

	    /**************************************************************
	     * Select files to import
	     * ************************************************************/
	    IOFileHandler fileBrowser = new IOFileHandler();
	    FileNameExtensionFilter filter = new FileNameExtensionFilter("Tempo Output Files", "OUT", "out");
	    String[] filePaths = fileBrowser.selectFile(true, filter);

	    numberOfFiles = fileBrowser.getNumberOfFiles();
	    outFileFieldsArray = new OutFileFields[numberOfFiles];

	    /**************************************************************
	     * Import the csv file assuming default columns
	     * ************************************************************/
	    CsvImporter importer = new CsvImporter(tableColoumns);

	    /* import all the csv files to an array of outFileFields */
	    for (int i = 0; (i < filePaths.length) && (filePaths[i] != null); i++) {
		outFileFieldsArray[i] = importer.populateOutFileFields(filePaths[i]);
	    }

	    /**************************************************************
	     * Ask user to identify columns before finalizing the table
	     * ************************************************************/
	    UserAssistedParserPanelHandler parserPanelHandler = new UserAssistedParserPanelHandler(this,
		    outFileFieldsArray);
	    JPanel parserPanel = parserPanelHandler.getPanel();
	    startupFrame.setResizable(true);
	    draw(450, 50, 335, 450);
	    screensHolderPanel.add(parserPanel, PARSER_SCREEN_CARD);
	    CardLayout screenHolderPanelLayout = (CardLayout) screensHolderPanel.getLayout();
	    screenHolderPanelLayout.show(screensHolderPanel, PARSER_SCREEN_CARD);
	    startupFrame.setTitle("Column Identifier");
	    startupFrame.setResizable(false);
	    Vector tableColoumnsVector = parserPanelHandler.getColumnNames(outFileFieldsArray[0]);
	    tableColoumns = tableColoumnsVector.toArray();

	} else if (source.equals(utilitySelector)) {
	    String selectedItem = utilitySelector.getSelectedItem().toString();
	    if (selectedItem.equals(TEMPLATE_EDITOR)) {
		modeSelector.setEnabled(true);
		modeSelector.setForeground(Color.BLUE);
		modeSelector.setBackground(Color.WHITE);
	    } else {
		modeSelector.setEnabled(false);
		modeSelector.setForeground(Color.GRAY);
	    }
	}

    }

    private void drawStartupFrame() {
	startupFrame.setTitle(EXPERIMENT_SETUP + modeSelector.getSelectedItem());
	draw(xPosition, yPosition, width, height);
	setupConfigurationScreen();
    }

    protected void createTable(Vector newColumnVector) {

	tableColoumns = newColumnVector.toArray();
	/***************************************************************
	 * Add a table containing these values
	 * *************************************************************/
	TablePanelHandler tablePanelHandler = new TablePanelHandler(tableColoumns, outFileFieldsArray);
	JPanel tablePanel = tablePanelHandler.getPanel();

	startupFrame.setResizable(true);
	startupFrame.setExtendedState(startupFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
	screensHolderPanel.add(tablePanel, TABLE_SCREEN_CARD);
	CardLayout screenHolderPanelLayout = (CardLayout) screensHolderPanel.getLayout();
	screenHolderPanelLayout.show(screensHolderPanel, TABLE_SCREEN_CARD);
	startupFrame.setTitle("Tempo Output Importer/Analyzer");
	startupFrame.setResizable(false);
    }

    /**
     * @return
     */
    public static int getMode() {
	// TODO Auto-generated method stub
	return modeSelector.getSelectedIndex() + 1;
    }

}
